package kafeisc.dao;

import kafeisc.domain.User;
import kafeisc.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * @Classname UserDao
 * @Description TODO
 * @Date 20:55
 * @Created 
 */
public class UserDao {
   // 添加用户
   public void addUser(User user) throws SQLException {
      String sql = "insert into user(username,password,gender,email,telephone,introduce,activecode) values(?,?,?,?,?,?,?)";
      QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
      int row = runner.update(sql, user.getUsername(), user.getPassword(),
              user.getGender(), user.getEmail(), user.getTelephone(),
              user.getIntroduce(), user.getActiveCode());
      if (row == 0) {
         throw new RuntimeException();
      }
   }

   // 根据激活码查找用户
   public User findUserByActiveCode(String activeCode) throws SQLException {
      String sql = "select * from user where activecode=?";
      QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
      return runner.query(sql, new BeanHandler<User>(User.class), activeCode);

   }

   // 激活用戶
   public void activeUser(String activeCode) throws SQLException {
      String sql = "update user set state=? where activecode=?";
      QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
      runner.update(sql, 1, activeCode);
   }

   //根据用户名与密码查找用户
   public User findUserByUsernameAndPassword(String username, String password) throws SQLException {
      String sql="select * from user where username=? and password=?";
      QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
      return runner.query(sql, new BeanHandler<User>(User.class),username,password);
   }

   // 根据用户名查找用户密码和邮件(用于找回密码)
   public User findPasswordAndEmail(String username) throws SQLException {
      String sql = "select * from user where username=?";
      QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
      return runner.query(sql, new BeanHandler<User>(User.class),username);
   }

}
